package com.cn.xiaonuo.slbfinances.slborders.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cn.xiaonuo.common.entity.BusinessMessage;
import com.cn.xiaonuo.common.utils.StringUtils;
import com.cn.xiaonuo.core.util.RedisKeyUtil;
import com.cn.xiaonuo.dbs.core.annotation.DataSource;
import com.cn.xiaonuo.slbfinances.shopassets.entity.SlShopWalletLog;
import com.cn.xiaonuo.slbfinances.shopassets.mapper.SlShopWalletLogMapper;
import com.cn.xiaonuo.slbfinances.shopassets.mapper.SlShopWalletMapper;
import com.cn.xiaonuo.slbfinances.shopassets.entity.SlShopWalletLog;
import com.cn.xiaonuo.slbfinances.shopassets.mapper.SlShopWalletLogMapper;
import com.cn.xiaonuo.slbfinances.slborders.entity.CommonOrder;
import com.cn.xiaonuo.slbfinances.slborders.entity.SlShopWalletOrder;
import com.cn.xiaonuo.slbfinances.slborders.mapper.CmShopWalletMapper;
import com.cn.xiaonuo.slbfinances.slborders.mapper.SlShopWalletOrderMapper;
import com.cn.xiaonuo.slbfinances.slborders.mapper.SlWithdrawalDetailedMapper;
import com.cn.xiaonuo.slbfinances.slborders.param.CommonOrderParam;
import com.cn.xiaonuo.slbfinances.slborders.service.ICoverageShopWalletService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.compress.utils.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
public class CoverageShopWalletServiceImpl extends ServiceImpl<CmShopWalletMapper,String> implements ICoverageShopWalletService {

    @Autowired
    private SlShopWalletOrderMapper slShopWalletOrderMapper;

    @Autowired
    private CmShopWalletMapper cmShopWalletMapper;
    @Autowired
    private SlWithdrawalDetailedMapper slWithdrawalDetailedMapper;
    @Autowired
    private SlShopWalletLogMapper slShopWalletLogMapper;
    @Autowired
    private SlShopWalletMapper slShopWalletMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    @DataSource(name = "jyb_soole_data_hn")
    public BusinessMessage queryShopOrderList(CommonOrderParam slbOrderReqParam) {
        BusinessMessage message = new BusinessMessage();
        try {
            Integer pageSize = slbOrderReqParam.getPageSize();
            Integer pageNo = slbOrderReqParam.getPageNo();
            if (null == pageNo || Integer.valueOf(pageNo) <= 1) {
                pageNo = 1;
            }
            if (null == pageSize || Integer.valueOf(pageSize) <= 1) {
                pageSize = 10;
            }
            CommonOrder commonOrder=new CommonOrder();
            BeanUtil.copyProperties(slbOrderReqParam,commonOrder);
            PageHelper.startPage(pageNo,pageSize);
            List<Map<String, Object>> maps = cmShopWalletMapper.queryShopOrderList(commonOrder);
            if(maps!=null && maps.size()>=0){
                PageInfo<Map<String, Object>> pageInfos = new PageInfo<>(maps);
                message.setData(pageInfos);
                message.setSuccess(true);
                message.setCode("200");
                message.setMessage("查询成功");
                return message;
            }
        } catch (NumberFormatException e) {
            message.setSuccess(false);
            message.setMessage("查询失败");
            e.printStackTrace();
        }
        return message;
    }
    @Override
    @DataSource(name = "jyb_soole_data_hn")
    @Transactional(rollbackFor = {Exception.class})
    public BusinessMessage updateShopOrderStatus(String shopOrderIds,Integer userId
    ) {
        BusinessMessage message = new BusinessMessage();
        String lockKey= RedisKeyUtil.JYB_SHOP_ORDER_STATUS_+ userId;
        try {
            if(StringUtils.isBlank(shopOrderIds)){
                message.setCode("-1");
                message.setSuccess(false);
                message.setMessage("shopOrderIds不能为空");
                return message;
            }
            String[] split = shopOrderIds.split(",");
            Boolean lock = redisTemplate.opsForValue().setIfAbsent(lockKey,"1",15, TimeUnit.SECONDS);
            //操作人加锁,15秒
            if (!lock) {
                message.setSuccess(false);
                message.setCode("-1");
                message.setMessage("订单处理中,请勿重复提交!");
                return message;
            }

            List<Integer> ids = Lists.newArrayList();
            for (String id : split) {
                ids.add(Integer.valueOf(id));
            }
            List<SlShopWalletOrder> slShopWalletOrders = slShopWalletOrderMapper.selectBatchIds(ids);
            // 状态还有已提现数据, 则返回
            List<Integer> payStatusList = slShopWalletOrders.stream().map(SlShopWalletOrder::getPayStatus).collect(Collectors.toList());
            if(payStatusList.contains(1)){
                message.setCode("-1");
                message.setSuccess(false);
                message.setMessage("更新失败");
                return message;
            }

            Integer i = cmShopWalletMapper.updateShopOrderStatus(split);
            Integer j = slWithdrawalDetailedMapper.updateStatus(split);

            for (SlShopWalletOrder walletOrder : slShopWalletOrders) {
                Integer integer = slShopWalletMapper.updateRemit(walletOrder);
                if(integer<1){//一条打款失败, 全部回滚
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    message.setCode("-1");
                    message.setSuccess(false);
                    message.setMessage("打款失败");
                    return message;
                }
            }
            message.setCode("200");
            message.setSuccess(true);
            message.setMessage("成功更新："+i+"条");
            return message;
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            message.setSuccess(false);
            message.setMessage("更新失败");
            e.printStackTrace();
        }finally {
            redisTemplate.delete(lockKey);
        }
        return message;
    }

}
